import { mapState } from 'vuex'
import { timeFix } from '@/utils/util'
import TableLayout from '@/components/TableLayout'
import { getBoardAndCategoryListByParentId, deleteBoardByIds, deleteBoardCategoryByIds } from '@/api/dashboard/board'
import Breadcrumb from '@/components/Breadcrumb'
import AddBoard from './AddBoard'
import './index.less'

export default {
  data() {
    return {
      timeFix: timeFix(),
      formData: {
        name: '',
      },
      formJson: [
        {
          type: 'input',
          label: '名称',
          fieldName: 'name',
          extraConfig: {
            // className: "row",
          },
          dataType: String,
        },
      ],
      list: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableLoading: true,
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          width: 80,
          customRender: (text, record, index) => {
            const type = record.type === 1 ? 'file' : 'catalogue'
            return (
              <div onClick={() => this.handleRowClick(text, record)} style="cursor: pointer">
                <c-icon type={type} /> {text}
              </div>
            )
          },
        },
        {
          title: '描述',
          dataIndex: 'description',
          width: 80,
        },
        {
          title: '发布状态',
          dataIndex: 'status',
          width: 80,
          customRender: text => {
            const statusOptions = [
              {
                label: "未上线",
                value: 1
              },
              {
                label: "审核中",
                value: 2
              },
              {
                label: "已上线",
                value: 3
              }
            ]
            return statusOptions.find(status => status.value === text)?.label
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          width: 80,
        },
        {
          title: '创建人',
          dataIndex: 'createdUser',
          width: 80,
        },
        {
          title: '更新时间',
          dataIndex: 'updatedAt',
          width: 80,
        },
        {
          title: '操作',
          dataIndex: 'tool',
          width: 140,
          customRender: (text, record, index) => {
            const { id, type, key } = record
            if (type == 1) {
              return (
                <div>
                  <a-button onClick={() => this.handleEditClick([key], [record])}>
                    <c-icon type="edit" />
                    编辑
                  </a-button>
                  <a-button onClick={() => this.handleDetailsClick(id)}>
                    <c-icon type="details" />
                    预览
                  </a-button>
                </div>
              )
            } else {
              return (
                <div>
                  {/* <a-button><c-icon type="edit" />编辑</a-button>
                  <a-button><c-icon type="details" />预览</a-button> */}
                </div>
              )
            }
          },
        },
      ],
      parentId: 0,
      tableHeader: [
        <a-button
          key="approve-add"
          onClick={this.handleAddClick}
          action="add"
          v-action="lowCode:boardCategoryManager:add"
        >
          <c-icon type="add" />
          新增
        </a-button>,
        <a-button
          key="approve-delete"
          onClick={this.handleDeleteClick}
          action="delete"
          v-action="lowCode:boardCategoryManager:delete"
        >
          <c-icon type="delete" />
          删除
        </a-button>,
        <a-button
          key="approve-move"
          onClick={this.handleMoveClick}
          action="move"
          v-action="lowCode:boardCategoryManager:move"
        >
          <c-icon type="move" />
          移动
        </a-button>,
        <a-button
          key="approve-re-name"
          onClick={this.handleReNameClick}
          action="re-name"
          v-action="lowCode:boardCategoryManager:re-name"
        >
          <c-icon type="re-name" />
          重命名
        </a-button>,
      ],
      parentPathList: [],
      spinning: false,
    }
  },
  computed: {},
  created() {
    this.$message.success(this.timeFix)
  },
  mounted() {
    // this.getBoardAndCategoryList()
  },
  methods: {
    handleSearch(data, resolve) {
      data.params.parentId = this.parentId || 0
      getBoardAndCategoryListByParentId({ ...data })
        // .then(resolve)
        .then((res) => {
          resolve({
            ...res,
            records: res.records.map((item) => {
              return {
                ...item,
                key: `${item.type}-${item.id}`,
              }
            }),
          })
        })
    },
    handleAddClick(...args) {
      this.$refs.addBoardRef.show('add')
      console.log('add', ...args)
    },
    handleReNameClick(keys, nodes) {
      this.$refs.addBoardRef.show('reName', nodes[0])
    },
    handleMoveClick(keys, nodes) {
      this.$refs.addBoardRef.show('move', nodes[0])
    },
    handleDeleteClick(keys, nodes) {
      const boardList = nodes.filter((node) => node.type === 1)
      const categoryList = nodes.filter((node) => node.type === 2)
      this.$confirm({
        title: '是否确认删除',
        content: '删除分类会删除改分类下所有分类和仪表盘',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        maskClosable: false,
        onOk: () => {
          this.spinning = true
          const requests = []
          if (boardList.length > 0) {
            requests.push(
              deleteBoardByIds({
                ids: boardList.map((node) => node.id).join(','),
              })
            )
          }
          if (categoryList.length > 0) {
            requests.push(
              deleteBoardCategoryByIds({
                ids: categoryList.map((node) => node.id).join(','),
              })
            )
          }
          Promise.all(requests)
            .then(() => {
              this.$message.success('删除成功')
              this.spinning = false
              this.reSearch()
            })
            .catch(() => {
              this.spinning = false
            })
        },
      })
    },
    handleRowClick(text, record) {
      console.log(text, record, this.$refs.tableLayoutRef)
      if (record.type === 1) {
        this.$router.push({ path: '/dashboard/dashboardPreview', query: { id: record.id, type: 'preview' } })
      } else {
        this.parentId = record.id
        this.$refs.tableLayoutRef.resetSearch()
        this.$refs.breadcrumbRef.addNode(record)
      }
    },
    handleEditClick(keys, nodes) {
      if (keys.length !== 1) {
        this.$message.warn('请选择一项')
        return
      }
      this.$router.push({ path: '/dashboard/editDashboard', query: { id: nodes[0].id } })
    },
    handleSeleceCategory(node) {
      this.parentId = node.value
      this.$refs.tableLayoutRef.resetSearch()
    },
    reSearch() {
      this.$refs.tableLayoutRef.resetSearch()
    },
    handleDetailsClick(id) {
      this.$router.push({ path: '/dashboard/dashboardPreview', query: { id,  type: 'preview' } })
    },
  },
  render(h) {
    const { tableHeader, formJson, columns, handleSearch, handleSeleceCategory, reSearch, spinning } = this
    return (
      <div class="container">
        <a-spin spinning={spinning}>
          <TableLayout
            ref="tableLayoutRef"
            tableHeader={tableHeader}
            formJson={formJson}
            columns={columns}
            search={handleSearch}
            rowKey="key"
            scopedSlots={{
              formBottom: (props) => {
                return <Breadcrumb ref="breadcrumbRef" onSelect={handleSeleceCategory} />
              },
            }}
          ></TableLayout>
        </a-spin>

        <AddBoard ref="addBoardRef" onUpdate={reSearch} />
      </div>
    )
  },
}
